package coupon

import (
	"context"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/promotion/rpc/promotionclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type AttachProductToCouponLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAttachProductToCouponLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AttachProductToCouponLogic {
	return &AttachProductToCouponLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AttachProductToCouponLogic) AttachProductToCoupon(
	req *types.AttachProductToCouponReq,
) (*types.BaseMsgResp, error) {
	if req.CouponId == nil || *req.CouponId == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if (req.ProductId == nil || *req.ProductId == 0) && (req.BrandId == nil || *req.BrandId == 0) && (req.CategoryId == nil || *req.CategoryId == 0) {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	res, err := l.svcCtx.PromotionRpc.AttachProductToCoupon(l.ctx, &promotionclient.CouponTemplateProductInfo{
		CouponId:    req.CouponId,
		BrandId:     req.BrandId,
		CategoryId:  req.CategoryId,
		ProductId:   req.ProductId,
		ProductType: req.ProductType,
		Sort:        req.Sort,
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
